package com.example.common.config;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

@Configuration
public class LocalDateTimeConfig {

    // 自定义 LocalDateTime 反序列化器（支持 T 和 Z）
    public static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        private static final DateTimeFormatter[] FORMATTERS = new DateTimeFormatter[]{
                DateTimeFormatter.ISO_LOCAL_DATE_TIME,             // yyyy-MM-dd'T'HH:mm:ss
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),// yyyy-MM-dd HH:mm:ss
                DateTimeFormatter.ISO_OFFSET_DATE_TIME             // 带 Z 或 +08:00
        };

        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String text = p.getText();
            for (DateTimeFormatter formatter : FORMATTERS) {
                try {
                    if (formatter == DateTimeFormatter.ISO_OFFSET_DATE_TIME) {
                        return OffsetDateTime.parse(text, formatter).toLocalDateTime();
                    }
                    return LocalDateTime.parse(text, formatter);
                } catch (DateTimeParseException ignored) {}
            }
            throw new RuntimeException("无法解析日期: " + text);
        }
    }

    @Bean
    public ObjectMapper objectMapper() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        ObjectMapper objectMapper = builder.build();

        // 注册 Java 8 日期模块
        objectMapper.findAndRegisterModules();

        // 自定义反序列化器
        SimpleModule module = new SimpleModule();
        module.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
        objectMapper.registerModule(module);

        // 可选：序列化时格式化 LocalDateTime 输出
        objectMapper.configOverride(LocalDateTime.class)
                .setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd HH:mm:ss"));

        return objectMapper;
    }
}
